﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YY.Common;
using YY.UI.BaseDataSvc;

namespace YY.UI
{
    public partial class FeeFrm : BaseFrm
    {
        /// <summary>
        /// 用户源数据临时变量
        /// </summary>
        IEnumerable<TB_User> users = null;

        /// <summary>
        /// 通用分类数据临时变量
        /// </summary>
        IEnumerable<TB_Options> options = null;

        /// <summary>
        /// 客户源数据临时变量
        /// </summary>
        IEnumerable<TB_Clients> clients = null;

        /// <summary>
        /// 费用临时变量
        /// </summary>
        TB_Fee _Fee = null;

        public FeeFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new BaseDataClient();
        }

        private void VerifyFee_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            this.users = this.BaseDataProxy.FindUsers(null, null);
            this.clients = this.BaseDataProxy.FindClients(null, null, null, null, null);
            this.options = this.BaseDataProxy.FindOptions(null, null, null);
            initDgvColumns();
            init();
            search();
        }

        /// <summary>
        /// 控件数据初始化
        /// </summary>
        private void init()
        {
            this.dtpEDate.Value = DateTime.Now;
            this.dtpSDate.Value = DateTime.Now.AddDays(-7);

            Common.BindEnumToComboBox(this.cbBoxOrderStatus, typeof(EnumCommon.OrderStatus), null);
            this.cbBoxOrderStatus.DropDownStyle = ComboBoxStyle.DropDownList;
            Common.BindEnumToComboBox(this.cbBoxFeeType, typeof(EnumCommon.FeeType), null);
            this.cbBoxFeeType.DropDownStyle = ComboBoxStyle.DropDownList;
            Common.BindOptionsComboBox(this.cbBoxItem, this.options, EnumCommon.OptionType.费目类型);
            this.cbBoxItem.DropDownStyle = ComboBoxStyle.DropDownList;

            Common.ComboBoxBindDatas<TB_User>(this.cbBoxOP, this.users, "userName", "id");
            this.cbBoxOP.DropDownStyle = ComboBoxStyle.DropDownList;
            //this.cbBoxOP.KeyPress += new KeyPressEventHandler(cbBoxUser_KeyPress);
            Common.ComboBoxBindDatas<TB_User>(this.cbBoxBizMan, this.users, "userName", "id");
            this.cbBoxBizMan.DropDownStyle = ComboBoxStyle.DropDownList;
            //this.cbBoxBizMan.KeyPress += new KeyPressEventHandler(cbBoxUser_KeyPress);
        }

        /// <summary>
        /// 初始化表格列
        /// </summary>
        private void initDgvColumns()
        {

            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能

            DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
            DataGridViewCheckBoxHeaderCell cbHeader = new DataGridViewCheckBoxHeaderCell();
            colCB.HeaderCell = cbHeader;
            Common.AddDgvColumn(this.dataGridView1, colCB, "", "", true, false, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "Id", "费用明细id", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderId", "作业单id", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderCode", "作业单号", true, true, null);
            //DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
            //cbc.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
            //Common.BindEnumToDataGridViewComboBoxColumn(cbc, typeof(EnumCommon.OrderStatus));
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderStatus", "流程状态", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "BizMan", "业务员", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "BizManName", "业务员", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "FeeType", "费用类型", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "IsVerify", "审批", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "Item", "费目名称", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "ItemName", "费目名称", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "FeeCode", "账单号", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "Operator", "制单人", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OperatorName", "制单人", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "Amount", "金额", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "Unit", "币制", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "UnitName", "币制", true, true, null);

            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCalendarColumn(), "OPTime", "制单时间", true, true, null);

            cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);
        }

        private void cbHeader_OnCheckBoxClicked(bool isChecked)
        {
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
                row.Cells[0].Value = isChecked;
            this.dataGridView1.EndEdit();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            search();
        }

        /// <summary>
        /// 数据搜索
        /// </summary>
        private void search()
        {
            int? op = null;
            if (this.cbBoxOP.SelectedItem != null)
                op = (this.cbBoxOP.SelectedItem as TB_User).id;

            int? bizMan = null;
            if (this.cbBoxBizMan.SelectedItem != null)
                bizMan = (this.cbBoxBizMan.SelectedItem as TB_User).id;

            bool? isVerify = null;
            if (!string.IsNullOrEmpty(this.cbBoxIsVerify.Text))
                isVerify = this.cbBoxIsVerify.Text == "是";

            int? feeType = null;
            if (this.cbBoxFeeType.SelectedItem != null)
                feeType = (int)Enum.Parse(typeof(EnumCommon.FeeType), this.cbBoxFeeType.Text);

            int? item = null;
            if (this.cbBoxItem.SelectedItem != null)
                item = (this.cbBoxItem.SelectedItem as TB_Options).id;

            DateTime dtStart = this.dtpSDate.Value.Date;
            DateTime dtEnd = this.dtpEDate.Value.AddDays(1).Date.AddSeconds(-1);

            IEnumerable<QFee> datas = this.BaseDataProxy.FindFees(this.txtBoxOrderCode.Text, this.cbBoxOrderStatus.Text, bizMan, op, dtStart, dtEnd, feeType, this.txtBoxFeeCode.Text, item, null, isVerify);
            if (datas == null)
                this.dataGridView1.DataSource = null;
            else
                this.dataGridView1.DataSource = datas.ToList(); //ToDataTable 导致死循环
        }

        /// <summary>
        /// 用户选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBoxUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.users != null)
                {
                    TB_User[] users = this.users.Where(p => p.userName.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchUser(cbBox, users, this);
                }
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            TB_Order order = this.BaseDataProxy.GetOrder(Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[1].Value));
            EditFeeFrm frm = new EditFeeFrm();
            frm.ID = Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[1].Value);
            frm.EditMode = true;
            frm.Order = order;
            frm.FeeType = (EnumCommon.FeeType)Enum.Parse(typeof(EnumCommon.FeeType), this.dataGridView1.CurrentRow.Cells[1].Value.ToString());
            frm.ShowDialog(this);
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dataGridView1.RowCount > 0)
            {
                for (int i = 0; i < this.dataGridView1.RowCount; i++)
                {
                    if (!Common.IsDgvCellNull(this.dataGridView1.Rows[i].Cells[5].Value))
                    {
                        TB_User query = this.users.SingleOrDefault(p => p.id == Convert.ToInt32(this.dataGridView1.Rows[i].Cells[5].Value));
                        if (query != null)
                            this.dataGridView1.Rows[i].Cells[6].Value = query.userName;
                    }

                    if (!Common.IsDgvCellNull(this.dataGridView1.Rows[i].Cells[12].Value))
                    {
                        TB_User query1 = this.users.SingleOrDefault(p => p.id == Convert.ToInt32(this.dataGridView1.Rows[i].Cells[12].Value));
                        if (query1 != null)
                            this.dataGridView1.Rows[i].Cells[13].Value = query1.userName;
                    }

                    if (!Common.IsDgvCellNull(this.dataGridView1.Rows[i].Cells[9].Value))
                    {
                        TB_Options query2 = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.费目类型.ToString() && p.id == Convert.ToInt32(this.dataGridView1.Rows[i].Cells[9].Value));
                        if (query2 != null)
                            this.dataGridView1.Rows[i].Cells[10].Value = query2.name;
                    }

                    if (!Common.IsDgvCellNull(this.dataGridView1.Rows[i].Cells[15].Value))
                    {
                        TB_Options query3 = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.币制单位.ToString() && p.id == Convert.ToInt32(this.dataGridView1.Rows[i].Cells[15].Value));
                        if (query3 != null)
                            this.dataGridView1.Rows[i].Cells[16].Value = query3.name;
                    }
                }
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.cbBoxBizMan.SelectedIndex = -1;
            this.cbBoxFeeType.SelectedIndex = -1;
            this.cbBoxIsVerify.SelectedIndex = -1;
            this.cbBoxItem.SelectedIndex = -1;
            this.cbBoxOP.SelectedIndex = -1;
            this.cbBoxOrderStatus.SelectedIndex = -1;
            this.txtBoxFeeCode.Text = null;
            this.txtBoxOrderCode.Text = null;
        }

        private void btnAddFee_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtBoxOrderCode.Text))
            {
                MessageBox.Show("请输入要新增费用的作业单号！");
                this.txtBoxOrderCode.Focus();
                return;
            }

            if (this.cbBoxFeeType.SelectedItem == null)
            {
                MessageBox.Show("请选择要新增费用的类型！");
                this.cbBoxFeeType.Focus();
                return;
            }

            QOrder[] orders = this.BaseDataProxy.FindOrders(false, this.txtBoxOrderCode.Text, null, null, null, null, null, null, null, null, null, null, null, null);
            if (orders != null)
            {
                if (orders.Any())
                {
                    TB_Order order = this.BaseDataProxy.GetOrder(orders.FirstOrDefault().OrderId);
                    if (order != null)
                    {
                        EditFeeFrm frm = new EditFeeFrm();
                        frm.EditMode = false;
                        frm.Order = order;
                        frm.FeeType = (EnumCommon.FeeType)Enum.Parse(typeof(EnumCommon.FeeType), EnumCommon.FeeType.应付.ToString());
                        frm.ShowDialog(this);
                    }
                }
            }
            else
            {
                MessageBox.Show("作业单号不存在，请重新输入！");
                this.txtBoxOrderCode.Focus();
            }
        }

        /// <summary>
        /// 费用审批
        /// </summary>
        /// <param name="isVerify">是否批准</param>
        /// <returns></returns>
        private bool verifyFee(bool isVerify)
        {
            //if (this.Order.financier != SysLoginUserInfo.UserId)
            //{
            //    MessageBox.Show("对该单据没有审核权限！");
            //    return false;
            //}

            if (this._Fee != null)
            {
                this._Fee.isVerify = isVerify;
                this._Fee.verifyMan = SysLoginUserInfo.UserId;
                this._Fee.verifyTime = DateTime.Now;
                if (this.BaseDataProxy.UpdateFee(this._Fee))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 批量审批
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBatchApp_Click(object sender, EventArgs e)
        {
            string msg = "批准";
            if (MessageBox.Show("确认" + msg + "该费用吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                for (int i = 0; i < this.dataGridView1.RowCount; i++)
                {
                    if (this.dataGridView1.Rows[i].Cells[0].Value != null && this.dataGridView1.Rows[i].Cells[0].Value.ToString().Equals("True"))
                    {
                        this._Fee = this.BaseDataProxy.GetFee(Convert.ToInt32(this.dataGridView1.Rows[i].Cells[1].Value));
                        if (_Fee != null && verifyFee(!this._Fee.isVerify))
                        {
                            CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(this._Fee, Common.OperateType.Update);
                            if (this.dataGridView1.Rows[i].Cells[5].Value.ToString() == EnumCommon.FeeType.应收.ToString())
                                YY.Common.EventCommon.OnYSUdDGVEvnt(sender, arg);
                            else
                                YY.Common.EventCommon.OnYFUdDGVEvnt(sender, arg);
                        }
                        else
                        {
                            MessageBox.Show("费用审批失败");
                            return;
                        }
                    }
                }
                MessageBox.Show("费用已" + msg);
                this.search();
            }            
                
        }
    }
}
